<!-- 人口统计学信息 联系方式 ContactInformation-->
<template>
  <div class="page-center">
    <div class="medical-form">
      <el-form :model="formData" label-width="140px" class="info-form" label-position="left">
        <el-divider content-position="left">
          <h3>联系方式</h3>
        </el-divider>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="手机">
              <div class="display-value info-value">{{ display(formData.mobile) }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { phone } from '@/api/dataEntry/demographicInformation'

export default {
  name: 'ContactInformation',
  data() {
    return {
      formData: {
        patientId: null,
        mobile: ''
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters('patient', ['robustPatientId', 'patientFallbackData'])
  },
  watch: {
    robustPatientId: {
      handler(newId) {
        if (newId) {
          this.formData.patientId = newId
          this.loadData(newId)
        } else {
          this.resetForm()
        }
      },
      immediate: true
    }
  },
  async mounted() {
    // 如果当前没有患者信息，尝试从存储恢复
    if (!this.robustPatientId) {
      const restored = await this.restorePatientFromStorage()
      if (restored) {
        this.formData.patientId = restored.id || restored.patientId
        this.loadData(this.formData.patientId)
      }
    }
  },
  methods: {
    ...mapActions('patient', ['restorePatientFromStorage']),

    async loadData(patientId) {
      if (this.loading) return

      this.loading = true
      try {
        const res = await phone({ recordId: patientId })
        this.handleResponseData(res)
      } catch (error) {
        console.error('Failed to load contact information:', error)
        this.applyFallbackData()
      } finally {
        this.loading = false
      }
    },

    handleResponseData(res) {
      const payload = res?.data?.data ?? res?.data ?? res ?? {}

      // 统一处理响应数据
      this.formData.mobile = payload.mobile ?? payload.phone ?? payload.contactPhone ?? ''
    },

    applyFallbackData() {
      const patient = this.patientFallbackData
      if (patient) {
        this.formData.mobile = patient.mobile ?? patient.phone ?? patient.contactPhone ?? ''
      }
    },

    resetForm() {
      this.formData = {
        patientId: null,
        mobile: ''
      }
    },

    display(val) {
      if (val === null || val === undefined || String(val).trim() === '') return '-'
      return val
    }
  }
}
</script>

<!-- 引入共享样式 -->
<style src="@/styles/shared.css"></style>

<style scoped>
</style>
